import React from 'react'
import PropTypes from 'prop-types'
import { bindActionCreator } from './constqdx-redux'
export class Provider extends React.Component {
  static childContextTypes = {
    store: PropTypes.object
  }
  constructor(props, context){
    super(props, context)
    this.store = props.store
  }
  getChildContext(){
    return {
      store: this.store
    }
  }
  render(){
    return this.props.children
  }
}

export const connect = (mapStateToProps, mapDispatchToProps) => (Comp) => {
  return class WrapComponent extends React.Component{
    static contextTypes = {
      store: PropTypes.object
    }
    constructor(props, context){
      super(props, context)
      this.state = {
        props:{}
      }
    }
    componentDidMount() {
      const { store } = this.context
      store.subscribe(() => this.update())
      this.update()
    }
    update(){
      //此处的store是从父元素传递过来的，也就是已经使用过中间件的store，因此不可以直接自己去引入
      const {store} = this.context
      const stateProps = mapStateToProps(store.getState())
      const dispatchProps = bindActionCreator(mapDispatchToProps, store.dispatch)
      this.setState({
        props:{
          ...this.state.props,
          ...stateProps,
          ...dispatchProps
        }
      })
    }
    render() {
      return <Comp {...this.state.props} ></Comp>
    }
  }
}